package com.longxi.tianjintianbao.ui.presenter.login;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.HttpResult;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.greedao.controller.DataUserController;
import com.longxi.tianjintianbao.greedao.entity.User;
import com.longxi.tianjintianbao.model.PropertyCompany;
import com.longxi.tianjintianbao.ui.activity.login.ChangeAccountActivity;
import com.longxi.tianjintianbao.ui.activity.login.LoginActivity;
import com.longxi.tianjintianbao.ui.activity.main.MainActivity;
import com.longxi.tianjintianbao.ui.activity.repair_publish.SelectCommunityActivity;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.view.login.ILoginAtView;
import com.longxi.tianjintianbao.utils.DrawableUtils;
import com.longxi.tianjintianbao.utils.MyUtils;
import com.longxi.tianjintianbao.utils.NetUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class LoginAtPresenter extends BasePresenter<ILoginAtView> {

    long id = 0;
    User selectUser = null;
    PropertyCompany propertyCompany = null;
    boolean isRememberPwd = true;//默认记住密码 写入数据库

    public LoginAtPresenter(BaseActivity context) {
        super(context);
    }

    public void autoLogon(){
        if(MyApplication.loginUser!=null){
            Intent intent = new Intent(mContext,MainActivity.class);
            mContext.startActivity(intent);
            mContext.finish();
            return;
        }
        User isLogin = DataUserController.findByIslogin("1");
        if(isLogin != null){
//            MyApplication.IP = getSp("IP");
//            MyApplication.IPID = getSp("IPID");
//            MyApplication.COMPANY = getSp("COMPANY");

            if("".equals(MyApplication.IPID)){
                return;
            }
            getView().getEtUsername().setText(isLogin.getLoginUsername());
            getView().getEtPassword().setText(isLogin.getLoginPassword());
            login();
        }
    }

    /**
     * 登录
     * username 用户名
     * password 密码
     */
    public void login() {
        if("".equals(MyApplication.IP)){
            getIP();
            return;
        }

        String username = getView().getEtUsername().getText().toString().trim();
        String password = getView().getEtPassword().getText().toString().trim();
        if(TextUtils.isEmpty(username)){
            MyUtils.showToast(MyUtils.getString(R.string.username_not_empty));
            return;
        }

        if(TextUtils.isEmpty(password)){
            MyUtils.showToast(MyUtils.getString(R.string.password_not_empty));
            return;
        }

        mContext.showWaitingDialog(MyUtils.getString(R.string.load));
        JSONObject object = new JSONObject();
        try {
            object.put("username", username);
            object.put("password", password);
            object.put("identification", AppConst.identification);
//            object.put("identification", "1104a89792fa498b4fe");
            object.put("phonetype", "ANDROID");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ApiRetrofit.getInstance().login(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<HttpResult<User>>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(HttpResult<User> user) {
                mContext.hideWaitingDialog();
                if(user.getCode() != 0){
                    MyUtils.showToast(user.getMsg());
                    pgyCheck();
                    return;
                }
                insertOrUpdate(user.getData().get(0), Long.parseLong(MyApplication.IPID), username, password);
            }
        });
    }

    public void goHome(User user){
//        JPushInterface.setAlias(mContext, AppConst.IntentRequstCode.JPUSH_INTERFACE_SEQUENCE, user.getLoginUsername());//极光绑定
//        TagAliasOperatorHelper.getInstance().handleAction(mContext, AppConst.IntentRequstCode.JPUSH_INTERFACE_SEQUENCE, user.getLoginUsername());
        MyApplication.loginUser = user;
        mContext.hideWaitingDialog();
        MyUtils.showToast("登录成功");
        Intent intent = new Intent(mContext, MainActivity.class);
        if("".equals(user.buildid) || user.buildid == null){
            intent = new Intent(mContext, SelectCommunityActivity.class);
            mContext.startActivityForResult(intent, AppConst.IntentRequstCode.ACTIVITY_SELECT_COMMUNITY);
        }else{
            mContext.startActivity(intent);
            mContext.finish();
        }
    }

    /**
     * 更新或插入用户用户
     * @param user
     */
    public void insertOrUpdate(User user, long iptype, String username, String password){

        //讲选择的ip存储到用户喜好中
        saveSp("IP", MyApplication.IP);
        saveSp("IPID", MyApplication.IPID);
        saveSp("COMPANY", MyApplication.COMPANY);

        DataUserController.updateAllByIsLogin();

        if(!isRememberPwd){
            goHome(user);
            return;
        }

        user.setIsLogin("1");//是否通过该账号登录
        user.setIptype(iptype);
        user.setLoginUsername(username);//登录账号
        user.setLoginPassword(password);//登录密码
        user.setUpdateTime(new Date());
        User userOld = DataUserController.findUserByIptypeAndUserid(user);
        if(userOld != null){
            user.setId(userOld.getId());
            DataUserController.updateUser(user);
        }else{
            DataUserController.insertUser(user);
        }
        goHome(user);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != mContext.RESULT_OK) {
            return;
        }

        switch (requestCode) {
            case AppConst.IntentRequstCode.ACTIVITY_SELECT_COMMUNITY:
                mContext.jumpToActivity(MainActivity.class);
                mContext.finish();
                break;
            case AppConst.IntentRequstCode.ACTIVITY_CHANGE_ACCOUNT:
                if(!getUser(data)){
                    return;
                }
                getView().getEtUsername().setText(selectUser.getLoginUsername());
                getView().getEtPassword().setText(selectUser.getLoginPassword());
                login();
                break;
            case AppConst.IntentRequstCode.ACTIVITY_OFFLINE_MODE:
                if(!getUser(data)){
                    return;
                }
                insertOrUpdate(selectUser, selectUser.getIptype(), selectUser.getLoginUsername(), selectUser.getLoginPassword());
                break;
        }
    }

    OptionsPickerView pvCustomOptions;
    /**
     * 获取ip 其实可以从网络获取过来
     */
    public void getIP() {
        if(pvCustomOptions != null){
            pvCustomOptions.show();
            return;
        }
        pvCustomOptions = new OptionsPickerBuilder(mContext, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                getCompanyIp(PropertyCompany.getData().get(options1));
                if(!"".equals(getView().getEtUsername().getText().toString()) && !"".equals(getView().getEtPassword().getText().toString())){
                    login();
                }
            }
        })
        .setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
            @Override
            public void customLayout(View v) {
                final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                final TextView tvTitle = (TextView) v.findViewById(R.id.tv_title);
                tvTitle.setText("请选择物业公司");
                ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                tvSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvCustomOptions.returnData();
                        pvCustomOptions.dismiss();
                    }
                });

                ivCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvCustomOptions.dismiss();
                    }
                });
            }
        })
        .isDialog(true)
        .build();

        if(PropertyCompany.getData().size() == 1){//判断是不是只有一个物业公司 是的话直接始用这一个地址
            getCompanyIp(PropertyCompany.getData().get(0));
            login();
            return;
        }

        pvCustomOptions.setPicker(PropertyCompany.getData());//添加数据
        pvCustomOptions.show();
    }

    /**
     * 切换后修改界面以及配置
     * @param propertyCompany
     */
    public void getCompanyIp(PropertyCompany propertyCompany){
        MyApplication.IP = propertyCompany.getIP();
        MyApplication.IPID = propertyCompany.getIPID();
        MyApplication.COMPANY = propertyCompany.getName();
        ApiRetrofit.clearInstance();//清除ApiRetrofit
        getView().getBtnLogin().setText("登录" + propertyCompany.getName() + "管理系统");
    }

    /**
     * 去账户切换Activity
     */
    public void toChangeAccountActivity() {
        Intent intent = new Intent(mContext, ChangeAccountActivity.class);
        int requestCode = AppConst.IntentRequstCode.ACTIVITY_CHANGE_ACCOUNT;
        if(!NetUtils.isNetworkAvailable(mContext)){
            intent.putExtra(AppConst.TITLE, "请选择离线账号");
            requestCode = AppConst.IntentRequstCode.ACTIVITY_OFFLINE_MODE;
        }
        mContext.startActivityForResult(intent, requestCode);
    }

    /**
     * 离线模式
     */
    public void offlineMode() {
        if(NetUtils.isNetworkAvailable(mContext)){
            getView().getTvChangeAccount().setText("切换账号");
        }else{
            getView().getTvChangeAccount().setText("离线模式");
        }

    }

    /**
     * 你懂的 拿用户数据 根据id
     * @return
     */
    public boolean getUser(Intent data){
        if(data == null){
            return false;
        }
        id = data.getLongExtra("id", 0);
        if(id == 0){
            return false;
        }
        selectUser = DataUserController.findById(id);
        if(selectUser == null){
            return false;
        }
        propertyCompany = (PropertyCompany)PropertyCompany.getData2().get(String.valueOf(selectUser.getIptype()));
        //返回的分别是三个级别的选中位置
        getCompanyIp(propertyCompany);
        return true;
    }

    /**
     * 是否记住密码操作
     */
    public void rememberPwd() {
        if(isRememberPwd){
            isRememberPwd = false;
            getView().getTvRememberPwd().setCompoundDrawables(DrawableUtils.getDrawable(R.mipmap.ic_select_normal, 1), null, null, null);
        }else{
            isRememberPwd = true;
            getView().getTvRememberPwd().setCompoundDrawables(DrawableUtils.getDrawable(R.mipmap.ic_select_press, 1), null, null, null);
        }
    }

    @Override
    public void detachView() {
        super.detachView();
        this.pvCustomOptions = null;
        this.selectUser = null;
        this.propertyCompany = null;
    }
}
